package org.xiaomao.mongodb;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.alibaba.fastjson.JSON;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class MiniMongodb {

	/**
	 * 创建数据库
	 * 
	 * @param path
	 * @throws Exception
	 */
	public void createDataBase(String path) throws Exception {
		// 创建Document对象
		Document document = DocumentHelper.createDocument();
		// 创建根节点
		Element root = document.addElement("database");
		// 创建子节点
		Element tab1 = root.addElement("table");
		// 创建对象属性
		tab1.addAttribute("name", "t_user");
		Element tab2 = root.addElement("table");
		tab2.addAttribute("name", "system.indexs");
		Element tab3 = root.addElement("table");
		tab3.addAttribute("name", "system.users");

		this.writer(path, document);

		System.out.println("----------create---database---success-------------------");
	}

	/**
	 * 添加数据
	 * 
	 * @param path
	 * @param tablename
	 * @param u
	 * @throws Exception
	 */
	public void saveData(String path, String tablename, Object u) throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new FileInputStream(path));
		Element root = document.getRootElement();

		List<Element> es = root.elements();
		for (Element e : es) {
			if (e.attributeValue("name").equals(tablename)) {
				String json = JSON.toJSONString(u);
				Map m = JSON.parseObject(json, Map.class);
				m.put("u_uid", UUID.randomUUID().toString());

				Element data = e.addElement("data");
				data.addText(JSON.toJSONString(m));
			}
		}

		this.writer(path, document);

		System.out.println("----------insert --- data --- success----------------------");
	}

	/**
	 * 修改数据
	 * 
	 * @param path
	 * @param tablename
	 * @param u
	 * @throws Exception
	 */
	public void updateData(String path, String tablename, Object u) throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new FileInputStream(path));
		Element root = document.getRootElement();

		List<Element> es = root.elements();
		for (Element e : es) {
			if (e.attributeValue("name").equals(tablename)) {
				Map newm = JSON.parseObject(JSON.toJSONString(u), Map.class);
				List<Element> ds = e.elements();
				for (Element d : ds) {
					Map m = JSON.parseObject(d.getText(), Map.class);
					if (m.get("u_uid").equals(newm.get("u_uid"))) {
						m.putAll(newm);

						e.remove(d);
						Element data = e.addElement("data");
						data.addText(JSON.toJSONString(m));
						break;
					}
				}
			}
		}

		this.writer(path, document);

		System.out.println("----------update --- data --- success----------------------");
	}

	public void deleteData(String path, String tablename, Object u) throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new FileInputStream(path));
		Element root = document.getRootElement();

		List<Element> es = root.elements();
		for (Element e : es) {
			if (e.attributeValue("name").equals(tablename)) {
				Map newm = JSON.parseObject(JSON.toJSONString(u), Map.class);
				List<Element> ds = e.elements();
				for (Element d : ds) {
					Map m = JSON.parseObject(d.getText(), Map.class);
					if (m.get("u_uid").equals(newm.get("u_uid"))) {
						e.remove(d);
						break;
					}
				}
			}
		}

		this.writer(path, document);

		System.out.println("----------delete --- data --- success----------------------");
	}

	public List<Map> listTableDatas(String path, String tablename) throws Exception {
		Element root = this.getRoot(path);

		List<Map> ms = new ArrayList<Map>();
		List<Element> es = root.elements();
		for (Element e : es) {
			if (e.attributeValue("name").equals(tablename)) {
				List<Element> ds = e.elements();
				for (Element d : ds) {
					Map m = JSON.parseObject(d.getText(), Map.class);
					ms.add(m);
				}
			}
		}

		return ms;
	}

	private void writer(String path, Document document) throws Exception {
		// 设置编码格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");

		// 输出
		XMLWriter writer = new XMLWriter(new FileOutputStream(path), format);
		writer.write(document);
		writer.close();
	}

	private Document getDocument(String path) throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new FileInputStream(path));
		return document;
	}

	private Element getRoot(String path) throws Exception {
		Document document = this.getDocument(path);
		Element root = document.getRootElement();
		return root;
	}
}
